package com.dk.shiro;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dk.pojo.TPerson;
import com.dk.service.MenuService;
import com.dk.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

//自定义登录(认证) ,授权的类
public class LoginUserRealm extends AuthorizingRealm {

    @Reference
    private UserService userService;

    @Reference
    private MenuService menuService;
    //授权的方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("shiro 的 授权方法");

        //动态的去授权 : 根据当前登录的用户进行授权
        TPerson person =(TPerson) SecurityUtils.getSubject().getPrincipal();

        //根据用户id查询当前用户所拥有的权限字符串
       List<String> perms= menuService.findPermissionByPid(person.getPid());

        //授权
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();

        authorizationInfo.addStringPermissions(perms);
        return authorizationInfo;
    }
    //认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        System.out.println("shiro 认证方法");

        //1.账号是否存在
        UsernamePasswordToken token =(UsernamePasswordToken) authenticationToken;

        TPerson user = userService.selectByName(token.getUsername());
        //账号不存在
        if (user ==null){
            return null;
        }

        //判断密码,如果密码正确,就能登录成功,错误就登录失败
        return new SimpleAuthenticationInfo(user,user.getPwd(), ByteSource.Util.bytes(user.getSalt()),"");
    }
}
